#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main()
{
  int pipefd[2]={0};
  if(pipe(pipefd)!=0)
  {
    perror("pipe perror!");
    return 1;
  }
  
  printf("pipefd[0]:%d\n",pipefd[0]);//0是读
  printf("pipefd[1]:%d\n",pipefd[1]);//1是写

  //父进程读取,子进程写
  if(fork()==0) //child
  {
    close(pipefd[0]);
    const char* msg="go to school!\n";
    while(1)
    {
      //pipe只要缓冲区还有,就会一直写入
      write(pipefd[1],msg,strlen(msg));
    }
  }

  //father
  close(pipefd[1]);
  while(1)
  {
    sleep(1);
    char buffer[64];
    ssize_t s=read(pipefd[0],buffer,sizeof(buffer)-1);//有数据就一直读
    if(s==0) break; //子进程关闭文件描述符
    else if(s>0)
    {
      buffer[s]=0;
      printf("父进程:子进程在说:%s\n",buffer);
    }
    else break;
    
  }
  return 0;

}
